package com.netty.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.extra.servlet.ServletUtil;
import com.cx.item.common.filter.CrossFilter;
import lombok.extern.log4j.Log4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 跨域拦截器
 */
@Component
@WebFilter(urlPatterns = "/*", filterName = "myCrossFilter")
@Order(0)
@Log4j
public class MyCrossFilter extends CrossFilter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse)res;
        HttpServletRequest request = (HttpServletRequest)req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "1728000");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With,X_Requested_With, Content-Type, Accept, userToken");
        Map<String, String> paramMap = ServletUtil.getParamMap(request);
        if (CollUtil.isEmpty(paramMap)) {
            log.debug(StrFormatter.format("<====>param----请求地址：{}", new Object[]{request.getRequestURI()}));
        } else {
            log.debug(StrFormatter.format("<====>param----请求地址：{}?{}", new Object[]{request.getRequestURI(), MapUtil.join(paramMap, "&", "=")}));
        }

        chain.doFilter(req, res);
    }
}
